# -*- coding: utf-8 -*-

import os
from lib.ucloud.ufile import downloadufile
import requests
import time
from src.ucloud.ufile_config import read_config

current_path = os.path.dirname(__file__)
projectPath = os.getcwd()


def read_log_file(file_name):
    public_key, private_key, bucket = read_config()

    # 构造下载对象，并设置公私钥
    handler = downloadufile.DownloadUFile(public_key, private_key)

    # 目标空间内要下载的文件名
    # 获取文件的访问url
    url = handler.public_download_url(bucket, file_name)
    # 上一行代码示例为公开空间，可使用私有空间对应方法并设置url过期时间
    # url = handler.private_download_url(bucket, key, expires=60)
    print(url)
    ret = requests.head(url)
    print(ret.headers)
    # 之后根据实际的业务逻辑处理返回结果的Header

    ext = file_name.split('.')[-1]
    dirs = projectPath.split('/src')[0] + "/src/ucloud/tmpfile/"
    try:
        if not os.path.exists(dirs):
            os.makedirs(dirs)
    except Exception as e:
        print("download_log makedirs error {0}".format(e))
    save_file = dirs + str(int(round(time.time() * 1000))) + "." + ext
    open(save_file, "w+").close()
    # 通过对象类的方法函数请求下载
    ret, resp = handler.download_file(bucket, file_name, save_file, isprivate=False)
    if resp.status_code == 200:
        return save_file
    else:
        if os.path.exists(save_file):
            os.remove(save_file)
        return None
